package com.test.baoxiudemo.battery;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;

public class MyServicer extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
	}

	@Override
	public void onStart(Intent intent, int startId) {
		new PollingThread().start();
	}

	class PollingThread extends Thread {
		@Override
		public void run() {
			Log.d("fbb", "battery service start");
			IntentFilter ifilter = new IntentFilter(
					Intent.ACTION_BATTERY_CHANGED);
			Intent battery = getApplicationContext().registerReceiver(null,
					ifilter);
			int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
			int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
			float batteryPct = level / (float) scale;
			long time = System.currentTimeMillis();
			
			BatteryInfo info = new BatteryInfo(time, level, null);
			BatteryInfoDBHelper helper = BatteryInfoDBHelper.getInstance(getApplicationContext());
			helper.add(info);
//			boolean needAdd = helper.needAdd(info);
//			if(needAdd){
//			}
			
//			SimpleDateFormat format = new SimpleDateFormat("MMdd,HH:mm:ss");
//			String time = format.format(new Date());
//			String result = time + " |" + level + "|" + scale + "|"
//					+ batteryPct + "|";
//			Log.d("fbb", "result:" + result);
//			FileWriter fileWriter = null;
//			BufferedWriter writer = null;
//			try {
//				File sdcard = Environment.getExternalStorageDirectory();
////				Log.d("fbb", sdcard);
//				File dir = new File(sdcard, "batteryTest");
//				if(!dir.exists()){
//					dir.mkdirs();
//				}
//				File file = new File(dir,"result.txt");
//				if (!file.exists()) {
//					boolean success = file.createNewFile();
//				}
//				fileWriter = new FileWriter(file, true);
//				writer = new BufferedWriter(fileWriter);
//				writer.write(result + "\n");
//				writer.flush();
//			} catch (IOException e) {
//				e.printStackTrace();
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					if (fileWriter != null) {
//						fileWriter.close();
//					}
//					if (writer != null) {
//						writer.close();
//					}
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("Service:onDestroy");
	}
}
